package cn.tedu.springmvc2.controller;

import cn.tedu.springmvc2.mapper.UserMapper;
import cn.tedu.springmvc2.pojo.dto.UserDTO;
import cn.tedu.springmvc2.pojo.entity.User;
import cn.tedu.springmvc2.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.jws.soap.SOAPBinding;
import java.util.Date;
import java.util.List;

/**
 * RESTful编码风格
 */
@RestController
@RequestMapping("/users")
public class RESTfulUserController {
    @Autowired
    private UserMapper userMapper;

    //注册 POST
    //@RequestMapping(value = "/users",method = RequestMethod.POST)
//    @PostMapping("/users")
    @PutMapping
    public  String add(UserDTO userDTO){
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new Date());
        int num=userMapper.insert(user);
        return num>0?"添加成功":"添加失败";
    }

    //修改 PUT
   // @RequestMapping(value = "/users",method = RequestMethod.PUT)
//    @PutMapping("/users")
    @PutMapping
    private String update(UserDTO userDTO){
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        int num=userMapper.updateByUsername(user);
        return num>0?"修改成功":"修改失败";
    }

    /*@PathVariable  从http://localhost:8080/users/8路径中找
    如果不加@PathVariable 则会DELETE的方法里找
    方法上的参数如果添加了注解：@PathVariable，那么就是表达这个参数的值从
    请求路径上获取，这个要配合在@RequestMapping的value指定地址的{参数名}"
    如果不添加@PathVariabl，SpringMVC框架还是会从请求的正文中解析参数
     */
    //@RequestMapping(value = "/users/{id}" ,method = RequestMethod.DELETE)
//    @DeleteMapping("/users/{id}")
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("id为"+id);
        int num=userMapper.deleteById(id);
        return num>0?"删除成功":"删除失败";
    }
//    @RequestMapping(value = "/users",method = RequestMethod.GET)
//    @GetMapping("/users")
    @GetMapping
    public List<UserVO> findAll(){
        return userMapper.findAll();
    }
//    @RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
//    @GetMapping("/users/{id}")
    @GetMapping("/{id}")
    public  UserVO find(@PathVariable Integer id){
       return userMapper.findById(id);
    }
}
